//
//  MateViewController.swift
//  EasyChat
//
//  Created by it-go-0367 on 2021/12/7.
//

import UIKit

class MateViewController: UIViewController {
    /** 顶部视图*/
    let topView : UIView = UIView.init()
    let titleLabel : UILabel = UILabel.init() //顶部Title
    /** 内容视图*/
    let mainView : UIView = UIView.init()
    /** 搜索框*/
    let searchField : UserDefineTextField = UserDefineTextField.init()
    let addtionView : UIView = UIView.init()
    /** 好友列表视图*/
    let mateKindView : UIScrollView = UIScrollView.init()
    let matesList : UITableView = UITableView.init()
    /** 分组信息*/
    var mateCategorys : [MateCategoryModel] = [MateCategoryModel]()
    //好友分类的标题数组
    let mateKindNames : [String] = ["好友", "分组", "群聊", "设备", "通讯录", "订阅号"]
    var mateKindButtons : [UIButton] = [UIButton]()
    var activeMateKindButton : UIButton = UIButton.init()

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        //初始化数据
        initData()
        //需要用这种方式设置tabbar图标
        self.tabBarItem = UITabBarItem.init(title: "朋友", image: UIImage.init(named: "mate_unsel")?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage.init(named: "mate_sel")?.withRenderingMode(.alwaysOriginal))
        self.view.backgroundColor = UIColor.init(red: 0.07, green: 0.64, blue: 1, alpha: 1)
        /** 顶部视图*/
        topView.frame = CGRect.init(x: 0, y: stateRegionHeight, width: screenWidth, height: 92-stateRegionHeight)
        topView.backgroundColor = UIColor.init(red: 0.07, green: 0.64, blue: 1, alpha: 1)
        self.view.addSubview(topView)
        /// 顶部Title
        titleLabel.frame = CGRect.init(x: (screenWidth-60)/2, y: 12, width: 60, height: 18)
        titleLabel.textAlignment = .center
        titleLabel.textColor = UIColor.white
        titleLabel.font = UIFont.systemFont(ofSize: 18)
        titleLabel.text = "联系人"
        topView.addSubview(titleLabel)
        /** 内容视图*/
        mainView.frame = CGRect.init(x: 0, y: topView.frame.maxY, width: screenWidth, height: safeScreenHeight)
        mainView.backgroundColor = UIColor.white
        self.view.addSubview(mainView)
        /// searchField
        searchField.frame = CGRect.init(x: 16, y: 8, width: screenWidth-16-16, height: 36)
        searchField.backgroundColor = UIColor.init(red: 0.94, green: 0.95, blue: 0.97, alpha: 1)
        searchField.layer.masksToBounds = true
        searchField.layer.cornerRadius = 18
        searchField.placeholder = "搜索"
        mainView.addSubview(searchField)
        //addtionView
        addtionView.frame = CGRect.init(x: 0, y: searchField.frame.maxY+12, width: screenWidth, height: 110+12)
        addtionView.backgroundColor = UIColor.init(red: 0.92, green: 0.92, blue: 0.97, alpha: 1)
        mainView.addSubview(addtionView)
        let newFriendView = MateAddtionView.init(title: "新朋友", frame: CGRect.init(x: 0, y: 0, width: screenWidth, height: 55))
        newFriendView.isUserInteractionEnabled = true
        let newFriendRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(newFriendHandler))
        newFriendView.addGestureRecognizer(newFriendRecognizer)
        addtionView.addSubview(newFriendView)
        //分割线
        let lineView = UIView.init(frame: CGRect.init(x: 0, y: (addtionView.frame.height-12)/2, width: screenWidth, height: 1))
        lineView.backgroundColor = UIColor.init(red: 0.9, green: 0.9, blue: 0.95, alpha: 1)
        addtionView.addSubview(lineView)
        let groupMessageView = MateAddtionView.init(title: "群消息", frame: CGRect.init(x: 0, y: lineView.frame.maxY, width: screenWidth, height: 55))
        groupMessageView.isUserInteractionEnabled = true
        let groupMessageRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(groupMessageHandler))
        groupMessageView.addGestureRecognizer(groupMessageRecognizer)
        addtionView.addSubview(groupMessageView)
        mateKindView.frame = CGRect.init(x: 0, y: addtionView.frame.maxY, width: screenWidth, height: 55)
        mateKindView.showsHorizontalScrollIndicator = false
        //按钮组的设计
        var fixX : CGFloat = 10.0
        for i in 0..<mateKindNames.count {
            let button = UIButton.init(frame: CGRect.init(x: fixX, y: 9, width: 60, height: 38))
            button.tag = i
            button.setTitle(mateKindNames[i], for: .normal)
            button.setTitleColor(UIColor.lightGray, for: .normal)
            button.setTitleColor(UIColor.init(red: 0.09, green: 0.74, blue: 0.98, alpha: 1), for: .selected)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
            button.layer.masksToBounds = true
            button.layer.cornerRadius = 12
            button.backgroundColor = UIColor.white
            button.addTarget(self, action: #selector(kindHandler(button:)), for: .touchUpInside)
            mateKindView.addSubview(button)
            mateKindButtons.append(button)
            fixX = fixX+60+10
        }
        //默认选中好友选项
        activeMateKindButton = mateKindButtons[1]
        activeMateKindButton.isSelected = true
        activeMateKindButton.backgroundColor = UIColor.init(red: 0.88, green: 0.97, blue: 0.99, alpha: 1)
        mateKindView.contentSize = CGSize.init(width: fixX, height: 55)
        mainView.addSubview(mateKindView)
        /// 好友列表
        matesList.frame = CGRect.init(x: 0, y: mateKindView.frame.maxY, width: screenWidth, height: 500)
        matesList.delegate = self
        matesList.dataSource = self
        matesList.separatorStyle = .none  //隐藏所有的分割线
        mainView.addSubview(matesList)
    }
    
    func initData() {
        let categoryNames : [String] = ["特别关心", "我的好友", "朋友", "家人", "同学"]
        //默认四个分组
        for categoryname in categoryNames {
            let category = MateCategoryModel.init()
            category.isOpen = false
            category.name = categoryname
            //生成随机数充当好友数量
            category.totleNum = Int(arc4random_uniform(150))
            category.onlineNum = Int(arc4random_uniform(UInt32(category.totleNum)))
            mateCategorys.append(category)
        }
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    
    @objc func kindHandler(button : UIButton) {
        //移除掉旧的选中效果，给新的按钮加上选中效果
        activeMateKindButton.isSelected = false
        activeMateKindButton.backgroundColor = UIColor.white
        activeMateKindButton = button
        activeMateKindButton.isSelected = true
        activeMateKindButton.backgroundColor = UIColor.init(red: 0.88, green: 0.97, blue: 0.99, alpha: 1)
        /// do something
        print(mateKindNames[button.tag])
    }
    
    @objc func newFriendHandler() {
        print("新朋友")
    }
    
    @objc func groupMessageHandler() {
        print("群消息")
    }
}
extension MateViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return mateCategorys[section].isOpen ? mateCategorys[section].totleNum : 0
    }
    
    /** 返回指定的列表项*/
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = MateCell.init(style: .default, reuseIdentifier: "matereuse")
        //cell.selectionStyle = .none  //取消默认的选中特效
        let cellInfo = MateModel.init()
        cellInfo.matePhote = "chat_mateProfile4"
        let photoIndex = arc4random_uniform(7)
        cellInfo.matePhote = "chat_mateProfile\(photoIndex)"
        cell.setMate(info: cellInfo)
        return cell;
    }
    
    /** 列表项的高度*/
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
    /** 列表项的点击事件*/
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(indexPath.row)
    }
    
    /** -----------------------------------------分组相关的回调函数------------------------------------------------------*/
    func numberOfSections(in tableView: UITableView) -> Int {
        mateCategorys.count
    }
    
    /** 分组Header的高度*/
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        44
    }
    
    /** 分组Header*/
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = MateCategoryView.init(reuseIdentifier: "reuseHeader")
        headerView.delegate = self
        headerView.setCategory(info: mateCategorys[section], index: section)
        return headerView
    }
}

extension MateViewController : EasyChatMateCategoryDelegate {
    
    /** 好友分组的点击事件*/
    func didSelect(categoryView: MateCategoryView, section: Int) {
        matesList.reloadData()
    }
}
